const express = require('express');
const commentRelationModel = require('../modules/comment_rela_tab');
const commentModel = require('../modules/comment_tab');
const userModel = require('../modules/user_tab');
const commentRouter = express.Router()
const Sequelize = require('sequelize')
const Op = Sequelize.Op

//根据评论内容、用户名、分页来模糊查询所有评论
commentRouter.get('/search',async(req,res,next) => {
    try{
        const page = parseInt(req.query.pageNum) || 1;
        const pageSize = parseInt(req.query.pageSize) || 10;
        const offset = (page - 1) * pageSize;

        const nickname = req.query.nickname
        const content = req.query.content

        let where = {
            is_delete: 0
        }
        let users = []
        let userIds = [] //存储用户id的数组
        if (content) {
            where.content = {
              [Op.like]: `%${content}%`
            }
          }
          if (nickname) {
            //根据昵称去用户表里面模糊查询
            users = await userModel.findAll({
              where: {
                nickname: {
                  [Op.like]: `%${nickname}%`
                },
                is_delete: 0
              },
              attributes: ['user_id', 'nickname'] // 选择用户id和昵称
            })
            // 提取用户ID数组
            userIds = users.map(user => user.user_id);
            if (userIds.length > 0) {
              where.user_id = {
                [Op.in]: userIds
              }
            }
          }

          const comments = await commentModel.findAll({
            raw: true,
            offset,
            limit: pageSize,
            where,
            include: [{
              model: userModel,
              as: 'user_tab',
              attributes: ['nickname'],
              where: { is_delete: 0 },
              required: true
            }]
        })
        res.json({
            code:1,
            msg:'请求成功',
            total:comments.length,
            data:comments
        })
    }catch(err){
        next(err)
    }
})
//根据id删除评论，假删除
commentRouter.post('/delete/one',async(req,res,next) => {
    try{
        const { comment_id } = req.query;
        const comment = await commentModel.findOne({ where: { comment_id, is_delete: 0 } });
        await comment.update({ is_delete: 1 });
        res.json({
          code: 1,
          msg: '请求成功',
        });
    }catch(err){
        next(err)
    }
})
//批量删除评论
commentRouter.post('/delete/amount',async(req,res,next) => {
  try {
    const { comments } = req.query;
    console.log('comments: ', comments);
    comments.forEach(async (item) => {
      const comment = await commentModel.findOne({ where: { comment_id: item.comment_id, is_delete: 0 } });
      await comment.update({ is_delete: 1 });
    })
    res.json({
      code: 1,
      msg: '请求成功'
    })
  } catch (err) {
    next(err);
  }
})
//根据id查看评论详情
commentRouter.get('/detail',async(req,res,next) => {
  try{
    const { comment_id } = req.query
     //查询评论
     const comment = await commentModel.findOne({ 
      where: { comment_id: comment_id, is_delete: 0 },
      include: [
        { 
            model: userModel, // 包含 userModel
            // attributes: ['nickname'], // 选择要包含的字段，比如昵称
            required: true // 如果用户不存在，评论也不应该返回
        },
        {
          model: commentModel, // 关联自己的模型
          as: 'parent_comment', // 使用别名指定子评论
          where: { is_delete: 0 }, // 过滤未删除的子评论
          include: [
            {
              model: commentModel, // 再次关联自己的模型
              as: 'parent_comment' // 使用别名指定父级评论
            }
          ]
        }
    ] 
    })
    res.json({
      code:1,
      msg:'请求成功',
      data:comment
    })
  }catch(err){
    next(err)
  }
})
// 错误处理中间件
commentRouter.use((err, req, res, next) => {

  res.status(500).json({
    code: 0,
    msg: '服务器内部错误',
  });
});
module.exports = commentRouter